<template>
  <div>
    <el-dialog
      title="部门选择"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      :width="isApp ? '98%' : '60%'"
    >
      <el-input
        v-model="filterText"
        prefix-icon="el-icon-search"
        placeholder="请输入部门名称并按下回车键进行筛选"
        @keyup.enter.native="handleFilterData"
      />
      <el-tree
        ref="tree"
        class="filter-tree"
        show-checkbox
        :data="deptData"
        :highlight-current="true"
        node-key="id"
        :props="defaultProps"
        :filter-node-method="filterNode"
        :check-strictly="!multi"
        @check="handleCheck"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    multi: {
      type: Boolean,
      default: false,
    },
    // 已选中的id列表
    selectedIds: {
      type: Array,
      default: function () {
        return [];
      },
    },
  },
  data() {
    return {
      dialogVisible: false,
      filterText: "",
      defaultProps: {
        children: "children",
        label: "title",
      },

      urlList: {
        dept: "/sys/sysDepart/queryTreeList",
      },
      url: { list: "/sys/sysDepart/queryTreeList" },

      selectData: {},
      deptData: [],
    };
  },
  computed: {
    isApp() {
      return sessionStorage.getItem("App") === "isApp";
    },
  },
  watch: {
    // filterText(val) {
    //   this.$refs.tree.filter(val)
    // },
    dialogVisible: {
      handler(newV) {
        if (newV) this.getDeptData();
      },
    },
  },
  methods: {
    handleFilterData() {
      this.$refs.tree.filter(this.filterText);
    },
    // 部门数据
    async getDeptData() {
      this.deptData = [
        {
          id: 1,
          title: "一级 1",
          children: [
            {
              id: 2,
              title: "二级 1-1",
              children: [
                {
                  id: 3,
                  title: "三级 1-1-1",
                },
              ],
            },
          ],
        },
      ];
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.title.indexOf(value) !== -1;
    },
    handleCheck(data, checkedList) {
      // 单选
      if (this.multi === false) {
        this.$refs.tree.setCurrentKey(data.id);
        this.$refs.tree.setCheckedKeys([data.id]);
      } else {
        console.log("我是多选");
      }
    },
    onConfirm() {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let idsList = checkedNodes.map((m) => m.id);
      this.$emit("onSelect", idsList);
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 500px;
  overflow: auto;
  box-sizing: border-box;
  padding: 10px 20px;
}
</style>
